package com.hiwan.platform.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Title: HttpUtil.java
 * @Package com.gexin.platform.biz.common.utils
 * @Description: Http操作辅助类
 * @author Yanjh
 * @date 2011-8-16 上午11:35:51
 * @version V1.0
 */
public class HttpUtil {

	private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

	static Logger log = LoggerFactory.getLogger(HttpUtil.class);
	static ObjectMapper mapper = new ObjectMapper();

	public void init() {

		HttpConnectionManagerParams httpConnectionManagerParams = new HttpConnectionManagerParams();
		httpConnectionManagerParams.setConnectionTimeout(1 * 60 * 1000);
		httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(1200);

		connectionManager.setParams(httpConnectionManagerParams);
	}

	public void destory() {
		connectionManager.shutdown();
	}

	/**
	 * 接口访问的最大重试次数
	 */
	public static final int SYS_GEXIN_MAX_HTTP_RETRIES = 3;

	/**
	 * @Title: httpPost
	 * @Description: 向指定Url post字符串内容
	 * @author Yanjh
	 * @param url
	 *        目标地址url
	 * @param postData
	 *        内容
	 * @return String 返回类型
	 */
	public static String httpPost(String url, String postData) {
		StringBuffer response = new StringBuffer();

		try {
			for (int i = 0; i < SYS_GEXIN_MAX_HTTP_RETRIES; i++) {
				HttpClient client = new HttpClient(connectionManager);
				PostMethod method = new PostMethod(url);
				StringBuffer rsp = new StringBuffer();

				// 设置Http Post数据
				ByteArrayInputStream bi = new ByteArrayInputStream(postData.getBytes("UTF-8"));
				InputStreamRequestEntity fr = new InputStreamRequestEntity(bi);
				method.setRequestEntity((RequestEntity) fr);
				try {
					client.executeMethod(method);
					// 下面是读取网站的返回网页，例如上传成功之类的
					if (method.getStatusCode() == HttpStatus.SC_OK) {
						// 读取为 InputStream，在网页内容数据量大时候推荐使用
						BufferedReader reader = new BufferedReader(new InputStreamReader(
								method.getResponseBodyAsStream(), "UTF-8"));
						String line;
						while ((line = reader.readLine()) != null) {
							rsp.append(line);
						}
						reader.close();
					}
				} catch (IOException e) {
					throw new RuntimeException("httpPost:[" + url + "] :" + StackTraceUtil.getStackTrace(e), e);
				} finally {
					method.releaseConnection();
				}

				if (rsp.length() > 0) {
					// 响应成功收到，请求完成
					response = rsp;
					break;
				}
			}

			return response.toString();
		} catch (Exception e) {
			throw new RuntimeException("httpPost:[" + url + "] :" + StackTraceUtil.getStackTrace(e), e);
		}
	}

	/***
	 * @Title: httpPostJSON
	 * @Description: 通过json进行http post
	 * @author wujl
	 * @param url
	 * @param data
	 * @return Map<String,Object> 返回类型
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> httpPostJSON(String url, Map<String, Object> data) {
		Map<?, ?> retMap = null;
		String response = null;
		try {
			response = httpPost(url, mapper.writeValueAsString(data));
			if (response == null || "".equals(response)) {
				return null;
			}

			retMap = mapper.readValue(response, Map.class);
			return (Map<String, Object>) retMap;
		} catch (Exception e) {
			throw new RuntimeException("httpPost:[" + url + "] [" + data + " ] [ " + response + "]:"
					+ StackTraceUtil.getStackTrace(e), e);
		}
	}
}
